package repository

import (
	"RocFamilySystem/models"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type SysMenuRepository struct {
	Db *gorm.DB
}

func init() {
	registerContainer["SysMenuRepository"] = &SysMenuRepository{}
}

func (r *SysMenuRepository) SetDB(db *gorm.DB) {
	r.Db = db
}

// InsertSysMenu 添加系统系统菜单
func (r *SysMenuRepository) InsertSysMenu(sysMenu *models.SysMenu) {

	//开启事务
	db := r.Db.Begin()
	defer handleTransactional(db)
	now := models.LocalTime(time.Now())
	sysMenu.CreateTime = &now
	err := db.Save(sysMenu).Error
	handleRepositoryErr(err, "添加系统菜单失败")
}

// DeleteSysMenu 删除系统系统菜单
func (r *SysMenuRepository) DeleteSysMenu(sysMenuId int) {
	db := r.Db.Begin()
	defer handleTransactional(db)

	err := db.Delete(&models.SysMenu{Id: &sysMenuId}).Error
	handleRepositoryErr(err, "添加系统菜单失败")
}

// DeleteSysMenuBatch 批量删除系统菜单
func (r *SysMenuRepository) DeleteSysMenuBatch(ids []string) {
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Where("id in (?)", ids).Delete(models.SysMenu{}).Error
	handleRepositoryErr(err, "删除系统缓存失败！")
}

// UpdateSysMenu 修改系统系统菜单
func (r *SysMenuRepository) UpdateSysMenu(sysMenu *models.SysMenu) {
	now := models.LocalTime(time.Now())
	sysMenu.UpdateTime = &now

	err := r.Db.Model(sysMenu).Omit("id", "create_time").Updates(sysMenu).Error
	handleRepositoryErr(err, "修改系统菜单失败")
}

// SelectSysMenu 查询系统系统菜单
func (r *SysMenuRepository) SelectSysMenu(sysMenu *models.SysMenu, pageNum, pageSize int) ([]models.SysMenu, int) {
	var (
		list  []models.SysMenu
		total int64
	)
	db := r.Db.Model(&models.SysMenu{})

	if sysMenu != nil {
		if sysMenu.MenuName != nil {
			db = db.Where("menu_name like ?", fmt.Sprintf("%%%s%%", *sysMenu.MenuName))
		}
	}
	//获取总数
	db.Count(&total)

	//获取列表
	db.Offset(pageSize * pageNum).Limit(pageSize)
	db.Order("weight asc").Find(&list)

	return list, int(total)
}

// SelectSysMenuById 查询系统菜单通过ID
func (r *SysMenuRepository) SelectSysMenuById(id int) models.SysMenu {
	var sysMenu models.SysMenu
	err := r.Db.First(&sysMenu, "id = ?", id).Error
	if err != nil {
		handleRepositoryErr(err, "查询失败")
	}
	return sysMenu
}
